package com.ced.sip.workflow.action;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Blob;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.snaker.engine.SnakerEngine;
import org.snaker.engine.access.Page;
import org.snaker.engine.access.QueryFilter;
import org.snaker.engine.entity.HistoryOrder;
import org.snaker.engine.entity.HistoryTask;
import org.snaker.engine.entity.Order;
import org.snaker.engine.entity.Process;
import org.snaker.engine.entity.Surrogate;
import org.snaker.engine.entity.Task;
import org.snaker.engine.entity.WorkItem;
import org.snaker.engine.helper.AssertHelper;
import org.snaker.engine.helper.StreamHelper;
import org.snaker.engine.helper.StringHelper;
import org.snaker.engine.helper.XmlHelper;
import org.snaker.engine.model.ProcessModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.ced.base.action.BaseAction;
import com.ced.base.exception.BaseException;
import com.ced.sip.common.BaseDataInfosUtil;
import com.ced.sip.common.DictStatus;
import com.ced.sip.common.UserRightInfoUtil;
import com.ced.sip.common.WorkFlowStatusMap;
import com.ced.sip.common.utils.DateUtil;
import com.ced.sip.common.utils.StringUtil;
import com.ced.sip.system.biz.IDepartmentsBiz;
import com.ced.sip.system.biz.IUsersBiz;
import com.ced.sip.system.entity.Departments;
import com.ced.sip.system.entity.Dictionary;
import com.ced.sip.system.entity.Users;
import com.ced.sip.workflow.base.entity.WFHistoryTask;
import com.ced.sip.workflow.base.entity.WFOrder;
import com.ced.sip.workflow.base.entity.WFProcess;
import com.ced.sip.workflow.base.entity.WFSurrogate;
import com.ced.sip.workflow.base.helper.SnakerHelper;
import com.ced.sip.workflow.base.service.SnakerEngineFacets;
import com.ced.sip.workflow.biz.IWfProcessNodeBiz;
import com.ced.sip.workflow.biz.IWfProcessStationRightsBiz;
import com.ced.sip.workflow.biz.IWfTextBiz;
import com.ced.sip.workflow.entity.WaitWorkItem;
import com.ced.sip.workflow.entity.WfProcessNode;
import com.ced.sip.workflow.entity.WfProcessStationRights;
import com.ced.sip.workflow.entity.WfText;


/**
 * 流程定义
 * @author yuqs
 * @since 0.1
 */
public class ProcessAction  extends BaseAction {
	@Autowired(required=true)
	private SnakerEngineFacets facets;
	@Autowired(required=true)
	private SnakerEngine engine;
	//流程节点分配处理人 服务类
	private IWfProcessNodeBiz iWfProcessNodeBiz;
	//流程节点岗位权限
	private IWfProcessStationRightsBiz iWfProcessStationRightsBiz; 
	//部门服务类
	private IDepartmentsBiz iDepartmentsBiz;
	//流程审批正文服务类
	private IWfTextBiz iWfTextBiz;
	//用户服务类
	private IUsersBiz iUsersBiz;
	
	
	//委托代理 实体类
	private Surrogate surrogate;
	private WFSurrogate wFSurrogate;
	//部门实体类
	private Departments departments;
	//用户实体类
	private Users users ;
	private WfText wfText;
	private WfProcessStationRights wfProcessStationRights;
	private List<WfProcessStationRights> wpnList;
	/**
	 * 查看流程列表
	 * 
	 * @return
	 * @throws BaseException
	 * @Action
	 */
	public String viewProcess() throws BaseException {
		return VIEW;
	}
	/**
	 * 流程定义查询列表
	 * @param model
	 * @return
	 */
	public String findProcess()  throws BaseException{
		Long comId=UserRightInfoUtil.getComId(getRequest());
		String displayName = getRequest().getParameter("displayName");
		HttpServletRequest request = ServletActionContext.getRequest();
		Page<Process> curPage = new Page<Process>(); 
		QueryFilter filter = new QueryFilter();
		if(StringHelper.isNotEmpty(displayName)) {
			filter.setDisplayName(displayName);
		}
		filter.setComId(comId);
		try{
			/************* 分页处理 ************/
			String startIndex = request.getParameter("startIndex");
			String pageSize = request.getParameter("pageSize");
			int skip;
			if (startIndex == null || "".equals(startIndex))
				startIndex = "0";
			skip =  Integer.parseInt( startIndex )/ Integer.parseInt( pageSize )+1;
			/************* 分页处理 ****************/
			curPage.setPageNo(skip);
			curPage.setPageSize(Integer.parseInt(pageSize));
			facets.getEngine().process().getProcesss(curPage, filter);			
			JSONObject jsons = new JSONObject();
			List<WFProcess> list= new ArrayList<WFProcess>();
			for(int i=0;i<curPage.getResult().size();i++){
				WFProcess pro = new WFProcess();
				BeanUtils.copyProperties(curPage.getResult().get(i), pro);
				if(StringUtil.isNotBlank(pro.getState())){
					pro.setStateName(WorkFlowStatusMap.getWorkflowStatus(String.valueOf(pro.getState())));
				}
				list.add(pro);
			}
				this.getRollPageDataTables().setRowCount((int)curPage.getTotalCount());
				this.getPagejsonDataTables(list);
			
	    }catch (Exception e) {
			e.printStackTrace();
	    }
	    return null;
	}
	
	public String forAddProcessInit(){
		return "";
	}


	public String processInit() {
		facets.initFlows();
		return "";//redirect:/snaker/process/list
	}
	
	
	/**
	 * 新建流程定义
	 * @param model
	 * @return
	 */
	public String processAdd(Model model) {
		return "";//snaker/processAdd
	}
	
	/**
	 * 新建流程定义[web流程设计器]
	 * @param model
	 * @return
	 */
	public String processDesigner() {
		String processId = getRequest().getParameter("processId");
		if(StringUtils.isNotEmpty(processId)) {
			try{
				Process process = facets.getEngine().process().getProcessById(processId);
				AssertHelper.notNull(process);
				ProcessModel processModel = process.getModel();
				if(processModel != null) {
					String json = SnakerHelper.getModelJson(processModel);
					getRequest().setAttribute("process", json);
					//System.out.println(json);
				}
				getRequest().setAttribute("processId", processId);
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
		return "forAddPorcessInit";
	}
	
	/**
	 * 编辑流程定义
	 * @param model
	 * @return
	 */
	public String processEdit(Model model, @PathVariable("id") String id) {
		Process process = facets.getEngine().process().getProcessById(id);
		model.addAttribute("process", process);
		if(process.getDBContent() != null) {
            try {
                model.addAttribute("content", StringHelper.textXML(new String(process.getDBContent(), "UTF-8")));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
		return "";//snaker/processEdit
	}
	
	/**
	 * 根据流程定义ID，删除流程定义
	 * @param id
	 * @return
	 */
	//@RequestMapping(value = "delete/{id}", method=RequestMethod.GET)
	public String processDelete() {
		String id = this.getRequest().getParameter("id");
		facets.getEngine().process().undeploy(id);
		return VIEW;
	}
	
	
	/**
	 * 保存流程定义[web流程设计器]
	 * @param model
	 * @return
	 * @throws IOException 
	 */
	public String processDeploy() throws IOException {
		Long comId=UserRightInfoUtil.getComId(getRequest());
		String model = getRequest().getParameter("model");
		String id = getRequest().getParameter("id");
		PrintWriter writer = getResponse().getWriter();  
        boolean flag = false;
		InputStream input = null;
		try {
			String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + SnakerHelper.convertXml(model);
			//System.out.println("model xml=\n" + xml);
			input = StreamHelper.getStreamFromString(xml);
			if(StringUtils.isNotEmpty(id)) {
				facets.getEngine().process().redeploy(id, input,comId);
			} else {
				String ids = facets.getEngine().process().deploy(input,comId);
				System.out.println(ids);
			}
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		writer.print(flag);  
        writer.flush();  
        writer.close(); 
        return null;
	}
	
	public String processStart(Model model, String processName,Long comId) {
		facets.startInstanceByName(processName, null, "userId", null,comId);
		return "";//redirect:/snaker/process/list
	}
	
	public Object json() throws IOException {
		String orderId = getRequest().getParameter("orderId");
		Process process=null;
		List<Task> tasks=null;
		HistoryOrder order = facets.getEngine().query().getHistOrder(orderId);
		tasks = facets.getEngine().query().getActiveTasks(new QueryFilter().setOrderId(orderId));
		process= facets.getEngine().process().getProcessById(order.getProcessId());
		
		AssertHelper.notNull(process);
		ProcessModel model = process.getModel();
		Map<String, String> jsonMap = new HashMap<String, String>();
		if(model != null) {
			jsonMap.put("process", SnakerHelper.getModelJson(model));
		}
		
		if(tasks != null && !tasks.isEmpty()) {
			jsonMap.put("active", SnakerHelper.getActiveJson(tasks));
		}
		JSONObject json = new JSONObject();
		json.putAll(jsonMap);
		PrintWriter writer = getResponse().getWriter();  
        writer.print(json.toString());  
        writer.flush();  
        writer.close(); 
		return null;
	}
	public Object tip() throws BaseException{
		String orderId = getRequest().getParameter("orderId");
		String taskName = getRequest().getParameter("taskName");
		try{
		List<Task> tasks = facets.getEngine().query().getActiveTasks(new QueryFilter().setOrderId(orderId));
        StringBuilder builder = new StringBuilder();
        String createTime = "";
        for(Task task : tasks) {
            if(task.getTaskName().equalsIgnoreCase(taskName)) {
                String[] actors = facets.getEngine().query().getTaskActorsByTaskId(task.getId());
                for(String actor : actors) {
                    builder.append(BaseDataInfosUtil.convertLoginNameToChnName(actor)).append(",");
                }
                createTime = task.getCreateTime();
            }
        }
        if(builder.length() > 0) {
            builder.deleteCharAt(builder.length() - 1);
        }
        Map<String, String> data = new HashMap<String, String>();
        data.put("actors", builder.toString());
        data.put("createTime", createTime);
        JSONObject json = new JSONObject();
		json.putAll(data);
		PrintWriter writer = getResponse().getWriter();  
        writer.print(json.toString());  
        writer.flush();  
        writer.close(); 
		} catch (Exception e) {
			log("通过流程图获取流程节点信息错误！", e);
		}
		return null;
	}
	/**
	 * 根据OrderId查看流程实例
	 * @return
	 * @throws BaseException 
	 */
	public String display() throws BaseException {
		String orderId = getRequest().getParameter("orderId");
		String processId = getRequest().getParameter("processId");
		HistoryOrder order = facets.getEngine().query().getHistOrder(orderId);
		Task task = new Task();
		task.setOrderId(orderId);
		getRequest().setAttribute("order", order);
		List<WFHistoryTask> tasks = this.getHistoryTaskInfo(task.getOrderId());
		for(WFHistoryTask ht:tasks){
			ht.setOperatorCn(BaseDataInfosUtil.convertLoginNameToChnName(ht.getOperator()));
		}
		//List<HistoryTask> tasks = facets.getEngine().query().getHistoryTasks(new QueryFilter().setOrderId(orderId));
		if(order.getCreator().equals(UserRightInfoUtil.getUserName(this.getRequest())))
            getRequest().setAttribute("workFlow", true);
		else
			getRequest().setAttribute("workFlow", false);
		getRequest().setAttribute("tasks", tasks);
		this.getRequest().setAttribute("param", this.getRequest().getParameter("param"));
		this.getRequest().setAttribute("processId", processId);
		return "processView";
	}
	
	/**
	 * 流程监控页面（正在运行实例）
	 * @param model
	 * @param page
	 * @return
	 */
	public String viewOrder() {
		return "viewOrder";
	}
	
	/**
	 * 流程监控页面（正在运行实例）
	 * @param model
	 * @param page
	 * @return
	 */
	public String findOrder() {
		Page<Order> curPage = new Page<Order>();
		try{
			/************* 分页处理 ************/
		String orderNo = getRequest().getParameter("orderNo");
			String startIndex = getRequest().getParameter("startIndex");
			String pageSize = getRequest().getParameter("pageSize");
			int page;
			if (startIndex == null || "".equals(startIndex))
				startIndex = "0";
			page =  Integer.parseInt( startIndex )/ Integer.parseInt( pageSize )+1;
			curPage.setPageNo(page);
			curPage.setPageSize(Integer.parseInt(pageSize));
			if(StringUtil.isNotBlank(orderNo)){
				facets.getEngine().query().getActiveOrders(curPage, new QueryFilter().setOrderNo(orderNo));	
			}else{
				facets.getEngine().query().getActiveOrders(curPage, new QueryFilter());	
			}
			String wfName="";
			List<WFOrder> list= new ArrayList<WFOrder>();
			for(int i=0;i<curPage.getResult().size();i++){
				Order order = curPage.getResult().get(i);
				WFOrder wfOrder = new WFOrder();
				wfOrder.setId(order.getId());
				wfOrder.setProcessId(order.getProcessId());
				wfOrder.setCreator(order.getCreator());
				wfOrder.setCreateTime(order.getCreateTime());
				wfOrder.setLastUpdator(order.getLastUpdator());
				wfOrder.setLastUpdateTime(order.getLastUpdator());
				wfOrder.setOrderNo(order.getOrderNo());
				wfOrder.setVariable(order.getVariable());
				wfOrder.setVariableMap(order.getVariableMap());
				wfOrder.setVersion(order.getVersion());
				HistoryOrder hyOrder = facets.getEngine().query().getHistOrder(wfOrder.getId());
				wfOrder.setOrderStateName(WorkFlowStatusMap.getWorkflowOrderStatus(String.valueOf(hyOrder.getOrderState())));
				List<Task> listtask = facets.getEngine().query().getActiveTasks(new QueryFilter().setOrderId(wfOrder.getId()));
				if(listtask.size() > 0){
					Task task = listtask.get(0);
					wfOrder.setActionUrl(task.getActionUrl());
					wfOrder.setTaskId(task.getId());
					Process process = facets.getEngine().process().getProcessById(wfOrder.getProcessId());
					if(process!=null){
						wfOrder.setProcessDisplayName(process.getDisplayName());
					}
				}
				list.add(wfOrder);
			}
			if(list.size() > 0){
				this.getRollPageDataTables().setRowCount((int)curPage.getTotalCount());
				for(int i=0;i<list.size();i++){
					WFOrder wfOrder = list.get(i);
					wfOrder.setCreatorCn(BaseDataInfosUtil.convertLoginNameToChnName(wfOrder.getCreator()));
					wfOrder.setLastUpdatorCn(BaseDataInfosUtil.convertLoginNameToChnName(wfOrder.getLastUpdator()));
					wfText=new WfText();
					wfText.setOrderId(wfOrder.getId());
					wfName=iWfTextBiz.getWfText(wfText).getWfName();
					//设置标题
					wfOrder.setTaskTitle(wfName);
					users = new Users();
					users.setUserName(wfOrder.getCreator());
					List<Users> uList = this.iUsersBiz.getUsersList(users);
					if(uList!=null&&uList.size()>0){
						departments = this.iDepartmentsBiz.getDepartments(uList.get(0).getDepId());
						wfOrder.setDeptName(departments.getDeptName());
					}
				}
				this.getRollPageDataTables().setRowCount((int)curPage.getTotalCount());
			}
			this.getPagejsonDataTables(list);
	    }catch (Exception e) {
			e.printStackTrace();
	    }
	    return null;
	}
	
	/**
	 * 流程监控页面（已结束实例）
	 * @param model
	 * @param page
	 * @return
	 */
	public String viewHistoryOrder() {
		return "viewHistoryOrder";
	}
	
	/**
	 * 流程监控页面（已结束实例）
	 * @param model
	 * @param page
	 * @return
	 */
	public String findHistoryOrder() {
		try{
			
			String orderNo = getRequest().getParameter("orderNo");
			String startIndex = getRequest().getParameter("startIndex");
			String pageSize = getRequest().getParameter("pageSize");
			String wfName="";
			int page;
			if (startIndex == null || "".equals(startIndex))
				startIndex = "0";
			page =  Integer.parseInt( startIndex )/ Integer.parseInt( pageSize )+1;
			Page<HistoryOrder> curPage = new Page<HistoryOrder>();
			curPage.setPageNo(page);
			curPage.setPageSize(Integer.parseInt(pageSize));
			if(StringUtil.isNotBlank(orderNo)){
				facets.getEngine().query().getHistoryOrders(curPage, new QueryFilter().setOrderNo(orderNo).setState(0));	
			}else{
				facets.getEngine().query().getHistoryOrders(curPage, new QueryFilter().setState(0));	
			}
			List<WFOrder> list= new ArrayList<WFOrder>();
			for(int i=0;i<curPage.getResult().size();i++){
				HistoryOrder hyOrder = curPage.getResult().get(i);
				WFOrder wfOrder = new WFOrder();
				wfOrder.setId(hyOrder.getId());
				wfOrder.setProcessId(hyOrder.getProcessId());
				wfOrder.setCreator(hyOrder.getCreator());
				wfOrder.setCreateTime(hyOrder.getCreateTime());
				wfOrder.setEndTime(hyOrder.getEndTime());
				wfOrder.setOrderNo(hyOrder.getOrderNo());
				wfOrder.setVariable(hyOrder.getVariable());
				wfOrder.setVariableMap(hyOrder.getVariableMap());
				wfOrder.setOrderStateName(WorkFlowStatusMap.getWorkflowOrderStatus(String.valueOf(hyOrder.getOrderState())));
				Process process = facets.getEngine().process().getProcessById(hyOrder.getProcessId());
				wfOrder.setProcessDisplayName(process.getDisplayName());
				List<HistoryTask> listtask = facets.getEngine().query().getHistoryTasks(new QueryFilter().setOrderId(wfOrder.getId()));
				if(listtask.size() > 0){
					HistoryTask hyTask = listtask.get(0);
					wfOrder.setActionUrl(hyTask.getActionUrl());
					wfOrder.setTaskId(hyTask.getId());
				}
				list.add(wfOrder);
			}
			if(list.size() > 0){
				this.getRollPageDataTables().setRowCount((int)curPage.getTotalCount());
				for(int i=0;i<list.size();i++){
					WFOrder wfOrder = list.get(i);
					wfOrder.setCreatorCn(BaseDataInfosUtil.convertLoginNameToChnName(wfOrder.getCreator()));

					wfText=new WfText();
					wfText.setOrderId(wfOrder.getId());
					wfName=iWfTextBiz.getWfText(wfText).getWfName();
					//设置标题
					wfOrder.setTaskTitle(wfName);
					users = new Users();
					users.setUserName(wfOrder.getCreator());
					List<Users> uList = this.iUsersBiz.getUsersList(users);
					if(uList!=null&&uList.size()>0){
						departments = this.iDepartmentsBiz.getDepartments(uList.get(0).getDepId());
						wfOrder.setDeptName(departments.getDeptName());
					}
				}
				this.getRollPageDataTables().setRowCount((int)curPage.getTotalCount());
			}
			this.getPagejsonDataTables(list);
	    }catch (Exception e) {
			e.printStackTrace();
	    }
	    return null;
	}
	
	/**
	 * 代办项列表页面
	 * @param model
	 * @param page
	 * @return
	 */
	public String viewWaitWokItems() {
		return "viewOrder";
	}
	
	/**
	 * 代办项列表
	 * @param model
	 * @param page
	 * @return
	 */
	public String findWaitWokItems() {
		Page<WorkItem> curPage = new Page<WorkItem>();
		int taskType = 0;
		try{
			/************* 分页处理 ************/
			String startIndex = getRequest().getParameter("startIndex");
			String pageSize = getRequest().getParameter("pageSize");
			int page;
			if (startIndex == null || "".equals(startIndex))
				startIndex = "0";
			page =  Integer.parseInt( startIndex )/ Integer.parseInt( pageSize )+1;
			/************* 分页处理 ****************/
			curPage.setPageNo(page);
			curPage.setPageSize(Integer.parseInt(pageSize));
			List<String> list = new ArrayList<String>();
			list.add("admin");
			String[] assignees = new String[list.size()];
			list.toArray(assignees);
			facets.getEngine().query().getWorkItems(curPage, 
					new QueryFilter().setOperators(assignees).setTaskType(taskType));		
			List<WaitWorkItem> waitlist= new ArrayList<WaitWorkItem>();
			for(int i=0;i<curPage.getResult().size();i++){
				WaitWorkItem pro = new WaitWorkItem();
				BeanUtils.copyProperties(curPage.getResult().get(i), pro);
				if(StringUtil.isNotBlank(pro.getTaskState())){
					pro.setTaskTypeName(WorkFlowStatusMap.getWorkflowOrderStatus(String.valueOf(pro.getTaskState())));
				}
				List<Task> listtask = facets.getEngine().query().getActiveTasks(new QueryFilter().setOrderId(pro.getId()));
				if(listtask.size() > 0){
					Task task = listtask.get(0);
					pro.setActionUrl(task.getActionUrl());
					pro.setTaskId(task.getId());
				}
				waitlist.add(pro);
			}
				this.getRollPageDataTables().setRowCount((int)curPage.getTotalCount());
				this.getPagejsonDataTables(list);
			
	    }catch (Exception e) {
			e.printStackTrace();
	    }
	    return null;
	}
	
	/**
	 * 代办项列表页面
	 * @param model
	 * @param page
	 * @return
	 */
	public String viewHisWokItems() {
		return "viewOrder";
	}
	
	/**
	 * 代办项列表
	 * @param model
	 * @param page
	 * @return
	 */
	public String findHisWokItems() {
		Page<WorkItem> curPage = new Page<WorkItem>();
		int taskType = 0;
		try{
			/************* 分页处理 ************/
			String startIndex = getRequest().getParameter("startIndex");
			String pageSize = getRequest().getParameter("pageSize");
			int page;
			if (startIndex == null || "".equals(startIndex))
				startIndex = "0";
			page =  Integer.parseInt( startIndex )/ Integer.parseInt( pageSize )+1;
			/************* 分页处理 ****************/
			curPage.setPageNo(page);
			curPage.setPageSize(Integer.parseInt(pageSize));
			List<String> list = new ArrayList<String>();
			list.add("admin");
			String[] assignees = new String[list.size()];
			list.toArray(assignees);
			facets.getEngine().query().getHistoryWorkItems(curPage, 
					new QueryFilter().setOperators(assignees).setTaskType(taskType));		
			List<WaitWorkItem> waitlist= new ArrayList<WaitWorkItem>();
			for(int i=0;i<curPage.getResult().size();i++){
				WaitWorkItem pro = new WaitWorkItem();
				BeanUtils.copyProperties(curPage.getResult().get(i), pro);
				if(StringUtil.isNotBlank(pro.getTaskState())){
					pro.setTaskTypeName(WorkFlowStatusMap.getWorkflowOrderStatus(String.valueOf(pro.getTaskState())));
				}
				List<Task> listtask = facets.getEngine().query().getActiveTasks(new QueryFilter().setOrderId(pro.getId()));
				if(listtask.size() > 0){
					Task task = listtask.get(0);
					pro.setActionUrl(task.getActionUrl());
					pro.setTaskId(task.getId());
				}
				waitlist.add(pro);
			}
			
				this.getRollPageDataTables().setRowCount((int)curPage.getTotalCount());
				this.getPagejsonDataTables(list);
			
	    }catch (Exception e) {
			e.printStackTrace();
	    }
	    return null;
	}
	
	public String findWfOrder(){
		try{
			JSONObject json = new JSONObject();
			String orderNo = this.getRequest().getParameter("orderNo");
			String processId = this.getRequest().getParameter("processId");
			QueryFilter filter = new QueryFilter();
			filter.setOrderNo(orderNo);
			filter.setProcessId(processId);
			List<HistoryOrder> order = facets.getEngine().query().getHistoryOrders(filter);
			json.put("order", order);
			PrintWriter writer = this.getResponse().getWriter();  
	        writer.print(json.toString());  
	        writer.flush();  
	        writer.close();
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}

	/**
	 * 流程节点分配处理人初始化
	 * @return
	 * @throws BaseException
	 * @Action
	 */
	public String updateAssignUserToNodeInit() throws BaseException {

		try {
			Long comId = UserRightInfoUtil.getComId(getRequest());
			String processId = this.getRequest().getParameter("processId");
			Process process = facets.getEngine().process().getProcessById(processId);
			this.getRequest().setAttribute("process", process);
			//无法手动设置处理人的节点
			String nodeUsers = "initiator,initDepLeader,initCompLeader";
			//判断数据库是否已经存在该流程的节点配置信息
			WfProcessNode wfpn = new WfProcessNode();
			wfpn.setProcessId(processId);
			List<WfProcessNode> wfpnList = this.iWfProcessNodeBiz.getWfProcessNodeList(wfpn);
			//删除该流程旧的节点设置信息
			//for(WfProcessNode wfProcessNode:wfpnList){
			//	this.iWfProcessNodeBiz.deleteWfProcessNode(wfProcessNode);
			//}
			//获得流程信息xml
			if(wfpnList.size()==0){
			Blob blob = process.getContent();
			byte[] bytes = com.ced.sip.common.utils.StringUtil.BlobToByte(blob);
			XmlHelper xmHelpr = new XmlHelper();
			DocumentBuilder docBuilder = xmHelpr.createDocumentBuilder();
			Document doc = docBuilder.parse(new ByteArrayInputStream(bytes));
			NodeList nodeList = doc.getElementsByTagName("task");
			//保存该流程新的节点设置信息
			for(int i=0;i<nodeList.getLength();i++){
			     Node node1 = nodeList.item(i);
			     String name = node1.getNodeName();
			     WfProcessNode wfpNode = new WfProcessNode();
		    	 wfpNode.setProcessId(processId);
		    	 wfpNode.setNodeTagName(node1.getNodeName());
			     NamedNodeMap nodeMap = node1.getAttributes();
			     for(int j=0;j<nodeMap.getLength();j++){
			    	 Node node2 = nodeMap.item(j);
			    	 if(node2.getNodeName().equals("name")){
			    		 wfpNode.setNodeCode(node2.getNodeValue());
			    		 //System.out.println(name+"="+node2.getNodeName()+":"+node2.getNodeValue());
			    	 }
			    	 if(node2.getNodeName().equals("displayName")){
			    		 wfpNode.setNodeName(node2.getNodeValue());
			    		// System.out.println(name+"="+node2.getNodeName()+":"+node2.getNodeValue());
			    	 }
			    	 if(node2.getNodeName().equals("assignee")){
			    		 wfpNode.setNodeOperator(node2.getNodeValue());
			    		// System.out.println(name+"="+node2.getNodeName()+":"+node2.getNodeValue());
			    	 }
			     }
			     this.iWfProcessNodeBiz.saveWfProcessNode(wfpNode);
		    }}
			//列表显示
			this.setListValue(this.iWfProcessNodeBiz.getWfProcessNodeList(wfpn));
			//设置是否包含无法手动设置处理人的节点
			for(int i=0;i<this.getListValue().size();i++){
				WfProcessNode wfProcessNode = (WfProcessNode) this.getListValue().get(i);
				if(nodeUsers.indexOf(wfProcessNode.getNodeCode())>=0){
					wfProcessNode.setRemark("1");
				}
				if(StringUtil.isNotBlank(wfProcessNode.getNodeUserName()))
				{
					wfProcessNode.setNodeUserNameCn(BaseDataInfosUtil.convertLoginNameToChnName(wfProcessNode.getNodeUserName()));
				}
			}
			//获取岗位
			List<Dictionary> dictionaryList=BaseDataInfosUtil.getDictInfoToList(DictStatus.COMMON_DICT_TYPE_1717);
			 this.getRequest().setAttribute("dictionaryList", dictionaryList);
		} catch (Exception e) {
			log.error("流程节点分配处理人初始化错误！", e);
			throw new BaseException("流程节点分配处理人初始化错误！", e);
		}
		return "node_addInit";
	}
	
	/**
	 * 流程节点分配处理人
	 * @return
	 * @throws BaseException
	 * @Action
	 */
	public String updateAssignUserToNode() throws BaseException {

		try {
			String nodeInfo = this.getRequest().getParameter("nodeInfo");
			if(!StringUtils.isBlank(nodeInfo)){
				String[] nodes = nodeInfo.split("@");
				if(nodes!=null){
					for(int i=0;i<nodes.length;i++){
					String[] ids = nodes[i].split(":");
						if(!StringUtils.isBlank(ids[0])){
							WfProcessNode wfpNode = this.iWfProcessNodeBiz.getWfProcessNode(Long.parseLong(ids[0]));
							wfpNode.setNodeUserId(Long.parseLong(ids[1]));
							wfpNode.setNodeUserName(ids[2]);
							wfpNode.setUserOrigin(ids[3]);
							wfpNode.setUserType(Integer.parseInt(ids[4]));
							this.iWfProcessNodeBiz.updateWfProcessNode(wfpNode);
						}
					}
				}
				this.getRequest().setAttribute("operModule", "保存流程节点分配处理人");
				this.getRequest().setAttribute("message", "保存成功");
			}
			
		} catch (Exception e) {
			log.error("流程节点分配处理人错误！", e);
			throw new BaseException("流程节点分配处理人错误！", e);
		}
		return "success";
	}
	
	/**
	 * 查看流程节点处理人设置信息
	 * @return
	 * @throws BaseException
	 * @Action
	 */
	public String viewAssignUserToNodeDetail() throws BaseException {

		try {
			String processId = this.getRequest().getParameter("processId");
			Process process = facets.getEngine().process().getProcessById(processId);
			this.getRequest().setAttribute("process", process);
			WfProcessNode wfpn = new WfProcessNode();
			wfpn.setProcessId(processId);
			List<WfProcessNode> wfpnList = this.iWfProcessNodeBiz.getWfProcessNodeList(wfpn);
			for(WfProcessNode wfn:wfpnList){
				if(wfn.getUserType()==10){
				  wfn.setNodeUserNameCn(BaseDataInfosUtil.convertLoginNameToChnName(wfn.getNodeUserName()));
				}
			}
			this.setListValue(wfpnList);
		} catch (Exception e) {
			log.error("查看流程节点处理人设置信息错误！", e);
			throw new BaseException("查看流程节点处理人设置信息错误！", e);
		}
		return "node_detail";
	}
	
	/**
	 * 首页快捷键：查看委托代理列表
	 * @return
	 * @throws BaseException
	 * @Action
	 */
	public String viewSurrogateInfoMain() throws BaseException {

		try {
			List<Process> proList = facets.getEngine().process().getProcesss(new QueryFilter().setState(1));
			Map map = new HashMap();
			for(Process process:proList){
				map.put(process.getName(), process.getDisplayName());
			}
			this.getRequest().setAttribute("map", map);
			this.getRequest().setAttribute("mainType", "mainType");
		} catch (Exception e) {
			log.error("查看委托代理列表错误！", e);
			throw new BaseException("查看委托代理列表错误！", e);
		}
		return "surr_view";
	}
	
	/**
	 * 查看委托代理列表
	 * @return
	 * @throws BaseException
	 * @Action
	 */
	public String viewSurrogateInfo() throws BaseException {

		try {
			List<Process> proList = facets.getEngine().process().getProcesss(new QueryFilter().setState(1));
			Map map = new HashMap();
			for(Process process:proList){
				map.put(process.getName(), process.getDisplayName());
			}
			this.getRequest().setAttribute("map", map);
		} catch (Exception e) {
			log.error("查看委托代理列表错误！", e);
			throw new BaseException("查看委托代理列表错误！", e);
		}
		return "surr_view";
	}
	
	/**
	 * 查看委托代理列表
	 * @param model
	 * @return
	 */
	public String viewToSurrogateInfo()  throws BaseException{
		
		String displayName = getRequest().getParameter("displayName");
		Long comId=UserRightInfoUtil.getComId(getRequest());
				
		Page<Surrogate> curPage = new Page<Surrogate>(); 
		try{
			/************* 分页处理 ************/
			String startIndex = getRequest().getParameter("startIndex");
			String pageSize = getRequest().getParameter("pageSize");
			int page;
			if (startIndex == null || "".equals(startIndex))
				startIndex = "0";
			page =  Integer.parseInt( startIndex )/ Integer.parseInt( pageSize )+1;;
			/************* 分页处理 ****************/
			curPage.setPageNo(page);
			curPage.setPageSize(Integer.parseInt(pageSize));
			//获得委托代理信息列表
			QueryFilter filter = new QueryFilter();
			filter.setComId(comId);
			if(StringHelper.isNotEmpty(displayName)) {
				filter.setName(displayName);
			}
			if(!"admin".equals(UserRightInfoUtil.getUserName(getRequest()))&&!"mpsadmin".equals(UserRightInfoUtil.getUserName(getRequest()))){
				filter.setOperator(UserRightInfoUtil.getUserName(getRequest()));
			}
			List<Surrogate> sgList = facets.getEngine().manager().getSurrogate(curPage, filter);
			List<WFSurrogate> wsgList = new ArrayList<WFSurrogate>();
			if(sgList.size() > 0){
				for(Surrogate sg:sgList){
					wFSurrogate = new WFSurrogate();
					BeanUtils.copyProperties(sg, wFSurrogate);
					wFSurrogate.setOperatorCn(BaseDataInfosUtil.convertLoginNameToChnName(sg.getOperator()));
					wFSurrogate.setSurrogateCn(BaseDataInfosUtil.convertLoginNameToChnName(sg.getSurrogate()));
					Process process = facets.getEngine().process().getProcessByName(sg.getProcessName(),comId);
					if(process!=null) wFSurrogate.setProcessNameCn(process.getDisplayName());
					wsgList.add(wFSurrogate);
				}
			}
			this.getRollPageDataTables().setRowCount((int)curPage.getTotalCount());
			this.getPagejsonDataTables(wsgList);
	    }catch (Exception e) {
			e.printStackTrace();
			log.error("查看委托代理列表错误！", e);
			throw new BaseException("查看委托代理列表错误！", e);
	    }
	    return null;
	}
	
	/**
	 * 设置委托代理初始化
	 * @return
	 * @throws BaseException
	 * @Action
	 */
	public String saveSurrogateInfoInit() throws BaseException {

		try {
			
			if(!"admin".equals(UserRightInfoUtil.getUserName(getRequest()))&&!"mpsadmin".equals(UserRightInfoUtil.getUserName(getRequest()))){
				wFSurrogate = new WFSurrogate();
				wFSurrogate.setOperator(UserRightInfoUtil.getUserName(getRequest()));
				wFSurrogate.setOperatorCn(BaseDataInfosUtil.convertLoginNameToChnName(UserRightInfoUtil.getUserName(getRequest())));
			}
			
			this.getRequest().setAttribute("cuurDate", new Date());
			if(UserRightInfoUtil.ifSystemManagerRole(this.getRequest()))
			{//是否是系统管理员
				this.getRequest().setAttribute("adminType", "adminType");
			}else{
				this.getRequest().setAttribute("operator", UserRightInfoUtil.getUserName(this.getRequest()));
			}
			
		} catch (Exception e) {
			log.error("设置委托代理初始化错误！", e);
			throw new BaseException("设置委托代理初始化错误！", e);
		}
		return "surr_addInit";
	}
	
	/**
	 * 设置委托代理
	 * @return
	 * @throws BaseException
	 * @Action
	 */
	public String saveSurrogateInfo() throws BaseException {

		try {
			Long comId=UserRightInfoUtil.getComId(getRequest());
			String sgType = this.getRequest().getParameter("sgType");
			if(StringUtil.isNotBlank(sgType)){
				if("0".equals(sgType)){
					QueryFilter queryFilter=new QueryFilter();
					queryFilter.setComId(comId);
					queryFilter.setState(1);
					List<Process> proList = facets.getEngine().process().getProcesss(queryFilter);
					for(Process pro:proList){
						Surrogate sug = new Surrogate();
						sug.setOperator(surrogate.getOperator());
						sug.setSurrogate(surrogate.getSurrogate());
						sug.setSdate(surrogate.getSdate()+" 06:00");
						sug.setEdate(surrogate.getEdate()+" 18:00");
						sug.setOdate(DateUtil.getDefaultDateFormat(new Date()));
						sug.setProcessName(pro.getName());
						sug.setComId(comId);
						sug.setProcessId(pro.getId());
						facets.getEngine().manager().saveOrUpdate(sug);
					}
				}else{
					surrogate.setOdate(DateUtil.getDefaultDateFormat(new Date()));
					facets.getEngine().manager().saveOrUpdate(surrogate);
				}
			}
			this.getRequest().setAttribute("message", "保存成功");
			this.getRequest().setAttribute("operModule", "保存委托代理");
			
		} catch (Exception e) {
			log.error("设置委托代理错误！", e);
			throw new BaseException("设置委托代理错误！", e);
		}
		this.saveSurrogateInfoInit();
		
		return "surr_addInit";
	}
	public String updateSurrogateInfoInit() throws BaseException {

		try {
			
			surrogate = facets.getEngine().manager().getSurrogate(surrogate.getId());
			
			this.getRequest().setAttribute("operatorCn", BaseDataInfosUtil.convertLoginNameToChnName(surrogate.getOperator()));
			this.getRequest().setAttribute("surrogateCn", BaseDataInfosUtil.convertLoginNameToChnName(surrogate.getSurrogate()));
			
		} catch (Exception e) {
			log.error("修改委托代理初始化错误！", e);
			throw new BaseException("修改委托代理初始化错误！", e);
		}
		return "surr_updateInit";
	}
	/**
	 * 修改委托代理
	 * @return
	 * @throws BaseException
	 * @Action
	 */
	public String updateSurrogateInfo() throws BaseException {

		try {
			
			facets.getEngine().manager().saveOrUpdate(surrogate);
		
			this.getRequest().setAttribute("message", "修改成功");
			this.getRequest().setAttribute("operModule", "修改委托代理");
			
		} catch (Exception e) {
			log.error("修改委托代理错误！", e);
			throw new BaseException("修改委托代理错误！", e);
		}
		return "surr_updateInit";
	}
	
	/**
	 * 删除委托代理
	 * @return
	 * @throws BaseException
	 * @Action
	 */
	public String deleteSurrogateInfo() throws BaseException {

		try {
			String ids=this.getRequest().getParameter("ids");
			String[] surrId=ids.split(",");
			for(int i=0;i<surrId.length;i++)
			{
				if(StringUtil.isNotBlank(surrId[i])){
					facets.getEngine().manager().deleteSurrogate(surrId[i]);
				}
			}
			PrintWriter out = this.getResponse().getWriter();
			String message="删除成功";
			out.println(message);
			
			this.getRequest().setAttribute("message", "删除成功");
			this.getRequest().setAttribute("operModule", "删除委托代理");
			
		} catch (Exception e) {
			log.error("删除委托代理错误！", e);
			throw new BaseException("删除委托代理错误！", e);
		}
		return null;
	}
	/**
	 * 流程唤醒、终止、删除
	 * @return
	 * @throws BaseException
	 * @throws IOException 
	 * @Action
	 */
	public String updateOperateOrders() throws Exception {
		PrintWriter out = this.getResponse().getWriter();
		try {
			this.ajaxHeadInit();
			String orderId = this.getRequest().getParameter("orderId");
			String type = this.getRequest().getParameter("type");
			if(StringUtil.isNotBlank(orderId)){
				if("0".equals(type)){
					facets.getEngine().order().resume(orderId);
					out.print(0);
				}else if("1".equals(type)){
					facets.getEngine().order().terminate(orderId, SnakerEngine.ADMIN);
					out.print(0);
				}else if("2".equals(type)){
					facets.getEngine().order().cascadeRemove(orderId);
					wfText = new WfText();
					wfText.setOrderId(orderId);
					List<WfText> wtList = this.iWfTextBiz.getWfTextList(wfText);
					for(WfText wt:wtList){
						this.iWfTextBiz.deleteWfText(wt);
					}
					out.print(0);
				}
			}
		} catch (Exception e) {
			out.print(1);
			log.error("流程唤醒、终止、删除错误！", e);
			throw new BaseException("流程唤醒、终止、删除错误！", e);
		}
		return null;
	}
	
	/**
	 * 保存采购结果流程审批请示正文
	 * @return
	 * @throws BaseException 
	 * @Action
	 */
	public void saveWorkFlowText(String orderNo,String description) throws BaseException {
           try{
        	   WfText wfText = new WfText();
        		List<Order> orderList = facets.getEngine().query().getActiveOrders(new QueryFilter().setOrderNo(orderNo));
        		if(orderList!=null&&orderList.size()>0){
        			wfText.setOrderId(orderList.get(0).getId());
        			List<WfText> wftList = this.iWfTextBiz.getWfTextList(wfText);
        			for(WfText wft:wftList){
        				this.iWfTextBiz.deleteWfText(wft);
        			}
        		}
        		wfText.setWfText(description);
        		this.iWfTextBiz.saveWfText(wfText);
		} catch (Exception e) {
			log.error("保存采购结果流程审批请示正文错误！", e);
			throw new BaseException("保存采购结果流程审批请示正文错误！", e);
		}
		
	}
	/**
	 * 不同岗位管理不同组织页面初始化
	 * @return
	 * @throws BaseException
	 */
	public String saveStationInit() throws BaseException{
		try {
			Long comId=UserRightInfoUtil.getComId(this.getRequest());
			Long wpnId=Long.parseLong(this.getRequest().getParameter("wpnId"));
			wfProcessStationRights=new WfProcessStationRights();
			wfProcessStationRights.setWpnId(wpnId);
			List<WfProcessStationRights> list=this.iWfProcessStationRightsBiz.getWfProcessStationRightsList(wfProcessStationRights);
			this.getRequest().setAttribute("list", list);
			this.getRequest().setAttribute("wpnId", wpnId);
			
			//获取岗位
			List<Dictionary> dictionaryList=BaseDataInfosUtil.getDictInfoToList(DictStatus.COMMON_DICT_TYPE_1717);
			 this.getRequest().setAttribute("dictionaryList", dictionaryList);
			
		} catch (Exception e) {
			log.error("不同岗位管理不同组织页面初始化错误！", e);
			throw new BaseException("不同岗位管理不同组织页面初始化错误！", e);
		}
		return "saveStationInit";
	}
	/**
	 * 保存不同岗位管理不同组织
	 * @return
	 * @throws BaseException
	 */
	public String saveStation() throws BaseException{
		try {
			Long wpnId=Long.parseLong(this.getRequest().getParameter("wpnId"));
			for (int i = 0; i < wpnList.size(); i++) {
				wfProcessStationRights = wpnList.get(i);
				if (wfProcessStationRights.getWpsrId().equals(0L)) {
					wfProcessStationRights.setWpnId(wpnId);
                    this.iWfProcessStationRightsBiz.saveWfProcessStationRights(wfProcessStationRights);
				}else{
					wfProcessStationRights.setWpnId(wpnId);
                    this.iWfProcessStationRightsBiz.updateWfProcessStationRights(wfProcessStationRights);
				}
			}
			WfProcessNode wfProcessNode=this.iWfProcessNodeBiz.getWfProcessNode(wpnId);
			wfProcessNode.setUserType(13);
			this.iWfProcessNodeBiz.updateWfProcessNode(wfProcessNode);
		} catch (Exception e) {
			log.error("保存不同岗位管理不同组织错误！", e);
			throw new BaseException("保存不同岗位管理不同组织错误！", e);
		}
		return "success";
	}
	/**
	 * 不同岗位管理不同组织页面查看
	 * @return
	 * @throws BaseException
	 */
	public String viewStationDetail() throws BaseException{
		try {
			Long wpnId=Long.parseLong(this.getRequest().getParameter("wpnId"));
			wfProcessStationRights=new WfProcessStationRights();
			wfProcessStationRights.setWpnId(wpnId);
			List<WfProcessStationRights> list=this.iWfProcessStationRightsBiz.getWfProcessStationRightsList(wfProcessStationRights);
			this.getRequest().setAttribute("list", list);
			this.getRequest().setAttribute("wpnId", wpnId);		
			
			
		} catch (Exception e) {
			log.error("不同岗位管理不同组织页面查看错误！", e);
			throw new BaseException("不同岗位管理不同组织页面查看错误！", e);
		}
		return "viewStationDetail";
	}
	
	public SnakerEngineFacets getFacets() {
		return facets;
	}
	public void setFacets(SnakerEngineFacets facets) {
		this.facets = facets;
	}
	public SnakerEngine getEngine() {
		return engine;
	}
	public void setEngine(SnakerEngine engine) {
		this.engine = engine;
	}
	public IWfProcessNodeBiz getiWfProcessNodeBiz() {
		return iWfProcessNodeBiz;
	}
	public void setiWfProcessNodeBiz(IWfProcessNodeBiz iWfProcessNodeBiz) {
		this.iWfProcessNodeBiz = iWfProcessNodeBiz;
	}
	public Surrogate getSurrogate() {
		return surrogate;
	}
	public void setSurrogate(Surrogate surrogate) {
		this.surrogate = surrogate;
	}
	public WFSurrogate getwFSurrogate() {
		return wFSurrogate;
	}
	public void setwFSurrogate(WFSurrogate wFSurrogate) {
		this.wFSurrogate = wFSurrogate;
	}
	public IDepartmentsBiz getiDepartmentsBiz() {
		return iDepartmentsBiz;
	}
	public void setiDepartmentsBiz(IDepartmentsBiz iDepartmentsBiz) {
		this.iDepartmentsBiz = iDepartmentsBiz;
	}
	public IUsersBiz getiUsersBiz() {
		return iUsersBiz;
	}
	public void setiUsersBiz(IUsersBiz iUsersBiz) {
		this.iUsersBiz = iUsersBiz;
	}
	public Departments getDepartments() {
		return departments;
	}
	public void setDepartments(Departments departments) {
		this.departments = departments;
	}
	public Users getUsers() {
		return users;
	}
	public void setUsers(Users users) {
		this.users = users;
	}
	public IWfTextBiz getiWfTextBiz() {
		return iWfTextBiz;
	}
	public void setiWfTextBiz(IWfTextBiz iWfTextBiz) {
		this.iWfTextBiz = iWfTextBiz;
	}
	public IWfProcessStationRightsBiz getiWfProcessStationRightsBiz() {
		return iWfProcessStationRightsBiz;
	}
	public void setiWfProcessStationRightsBiz(
			IWfProcessStationRightsBiz iWfProcessStationRightsBiz) {
		this.iWfProcessStationRightsBiz = iWfProcessStationRightsBiz;
	}
	public List<WfProcessStationRights> getWpnList() {
		return wpnList;
	}
	public void setWpnList(List<WfProcessStationRights> wpnList) {
		this.wpnList = wpnList;
	}	
}
